<?php

if (!defined('RAIZ')) define('RAIZ', $_SERVER['DOCUMENT_ROOT']. '/neumo/'); 

require_once RAIZ . 'lib/main.php';
require_once RAIZ . 'db/db_mysql.php';

$page = $_POST['page']; // get the requested page
$limit = $_POST['rows']; // get how many rows we want to have into the grid
$sidx = $_POST['sidx']; // get index row - i.e. user click to sort
$sord = $_POST['sord']; // get the direction
$bsc_palabra = isset($_POST['searchString']) ? $_POST['searchString'] : ''; 
$bsc_campo= isset($_POST['searchField']) ? $_POST['searchField'] : ''; 
$bsc_Oper= isset($_POST['searchOper']) ? $_POST['searchOper'] : ''; 

(isset($_GET['modo']))or die('Error no se ha definido el GET de modo');

$modo= $_GET['modo'];
$usuario= get_sesion('id_usuario');


$responce = new stdClass;

if (!$sidx) $sidx = 1;

$db_objeto= new dbase_objeto;

//objeto_crea_filtro($tipo,$busca,$borrador,$aprobado, $perfil, $publicacion, $nopublicacion)
if ($modo){
  $filtro= objeto_crea_filtro(0, 0,1, 0, 0,1, 1);
  $result = mysql_query("SELECT COUNT(*) AS count FROM objetos WHERE autor= " . $usuario . ' AND '. $filtro);
}else{
  $filtro= objeto_crea_filtro(0,0,0, 0, 0,0, 0);
  $result = mysql_query("SELECT COUNT(*) AS count FROM objetos WHERE 1 ");
}
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $row['count'];

if ($count > 0) {
  $total_pages = ceil($count / $limit);
} else {
  $total_pages = 0;
}
if ($page > $total_pages) $page = $total_pages;

$start = $limit * $page - $limit; // do not put $limit*($page - 1)
$start= max($start,0);
$filtro.=  ' AND ' . convierte_operador_jquery($bsc_campo,$bsc_Oper,$bsc_palabra);

$sql_limite= $start . ", " . $limit;
$sql_order=  $sidx . " ". $sord;
$sql_campos=" 
  id_objeto, 
  titulo,
  concat(ifnull(apellidos,''), ', ', ifnull(nombre,'')) as nombre_autor,
  c.descripcion as nombre_tipo, 
  borrador,
  aprobado,
  NOT (borrador OR aprobado ) as pendiente, 
  date_format( fecha_creacion, '%d/%m/%Y') as ffecha_creacion, 
  date_format( fecha_publicacion, '%d/%m/%Y') as ffecha_publicacion,
  date_format( fecha_nopublicacion, '%d/%m/%Y') as ffecha_nopublicacion,
  date_format( fecha_borrar, '%d/%m/%Y') as ffecha_borrado
  ";

if ($modo){
  $sql= "SELECT " . $sql_campos . 
      "FROM objetos as a
       left outer join usuarios as b on a.autor=b.id_usuario
       join cfdtipos as c on c.id_tipo = a.tipo 
       WHERE autor= ". $usuario ." and " 
       . $filtro . " ORDER BY " . $sql_order . " LIMIT " . $sql_limite; 
}else{
  $sql= "SELECT " . $sql_campos . 
          " FROM objetos as a 
            left outer join usuarios as b on a.autor=b.id_usuario
            join cfdtipos as c on c.id_tipo = a.tipo WHERE (1=1) AND " 
      . $filtro . " ORDER BY " . $sql_order . " LIMIT " . $sql_limite; 
}
//@pendiente: Corregir que salgan datos cuando el usurio no exista

$result = mysql_query($sql) or die("Error en la SQL de objetos" . mysql_error());

$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;

$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $responce->rows[$i]['id'] = $row['id_objeto'];
  $responce->rows[$i]['cell'] = array($row['id_objeto'], $row['titulo'],$row['nombre_autor'],$row['nombre_tipo'],
                                      $row['borrador'],$row['aprobado'], $row['ffecha_creacion'], $row['ffecha_publicacion'],
                                      $row['ffecha_nopublicacion'],$row['ffecha_borrado'], $row['pendiente']);
  $i++;
}

$db_objeto->cierra();

echo json_encode($responce);


/*==============================================================================
 * Subrutinas
 */


?>